package com.sxkf.template.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sxkf.template.entity.PostLike;
import com.sxkf.template.entity.PostNotice;
import com.sxkf.template.entity.Product;
import com.sxkf.template.entity.ProductLike;
import com.sxkf.template.mapper.ProductLikeMapper;
import com.sxkf.template.mapper.ProductMapper;
import com.sxkf.template.service.ProductLikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.util.CheckEmptyUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 帖子点赞 服务实现类
 * </p>
 *
 * @author 杨玉龙
 * @since 2024-12-10 16:21:00
 */
@Service
public class ProductLikeServiceImpl extends ServiceImpl<ProductLikeMapper, ProductLike> implements ProductLikeService {

    @Resource
    private ProductLikeMapper productLikeMapper;

    @Resource
    private ProductMapper productMapper;

    @Override
    public void add(ProductLike productLike) {
        ProductLike one = getOne(new LambdaQueryWrapper<ProductLike>()
                .eq(ProductLike::getProductId, productLike.getProductId())
                .eq(ProductLike::getUserId, productLike.getUserId()));
        //如果已有点赞记录则取消点赞
        if (one != null){
            productMapper.update(null,new LambdaUpdateWrapper<Product>()
                    .setSql("like_count = like_count - 1")
                    .eq(Product::getId, productLike.getId()));
            removeById(one);
            return;
        }

        //如果未点赞则进行点赞
        save(productLike);
        productMapper.update(null,new LambdaUpdateWrapper<Product>()
                .setSql("like_count = like_count+1")
                .eq(Product::getId, productLike.getId()));
    }

    @Override
    public Boolean isAdd(String userId, String productId) {
        ProductLike one = getOne(new LambdaQueryWrapper<ProductLike>()
                .eq(ProductLike::getProductId, productId)
                .eq(ProductLike::getUserId, userId));
        //如果已有点赞记录则取消点赞
        return one != null;
    }
}
